/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "Parallel.h"
#include <stdlib.h>
// threading stuff
#include <intrin.h>
#include <windows.h>

#include "../Hogshead.Common.h"
//#include "SafeTaskQueue.h"
#include "TaskQueue.h"

namespace Hogshead
{
	namespace Common
	{
		LONGLONG* Parallel::_thread_masks = NULL;
		int* Parallel::_thread_id = NULL;
		volatile LONGLONG Parallel::_thread_states = 0;
		volatile bool Parallel::_finalizing = false;
		int Parallel::_worker_thread_count = 1;
		TaskQueue* Parallel::_task_queue = NULL;
		int Parallel::_cores = 1;

		void Parallel::yield()
		{
			SwitchToThread();
		}

		void Parallel::sleep(int in_millis)
		{
			Sleep(in_millis);
		}

		int Parallel::cores()
		{
			return _cores;
		}

		int Parallel::threadCount()
		{
			return  _worker_thread_count + 1;
		}

		void Parallel::join()
		{
			// join here
			while(_task_queue->size() | _thread_states)
				SwitchToThread();
			//hout << "done" << endl;
			//hout << "joined" << endl;
  		}

		void Parallel::forLoop(int in_from, int in_to, void (*in_func)(int, void*), void* in_data)
		{
			int task_count = in_to - in_from + 1;
			int tasks = Math::min(threadCount(), task_count);
			int incr = Math::max(1, task_count / threadCount());

			// this variable will get decremented on completion of each for batch
			volatile unsigned long for_tasks_left = tasks;

			// start on 1 because main thread handles the first bits
			for(int k = 1; k < tasks; k++)
			{
				int start = in_from + incr * k;
				int end;
				if(k == tasks-1)
					end = in_to;
				else
					end = in_from + incr * (k+1) - 1;
	
				for_parameters* params = new for_parameters();
				params->from = start;
				params->to = end;
				params->func =  in_func;
				params->data = in_data;
				params->for_tasks_left = &for_tasks_left;
				Task* task = new Task(Parallel::_for_batch, params);
				_task_queue->enqueue(task);
			}

			// dot the first 

			for(int j = in_from; j < in_from + incr; j++)
				in_func(j, in_data);
			InterlockedDecrement(&for_tasks_left);

			// yield while there are tasks left
			while(for_tasks_left != 0)
				Parallel::yield();

		}

		void Parallel::_for_batch(void* in_data)
		{
			for_parameters* params = (for_parameters*)in_data;
			for(int k = params->from; k <= params->to; k++)
				(*params->func)(k, params->data);
			InterlockedDecrement(params->for_tasks_left);
			delete params;
		}

		void Parallel::initialize(int in_workers)
		{
			_finalizing = false;

			// get the number of cores
			SYSTEM_INFO sys_info;
			GetSystemInfo(&sys_info);
			_cores = sys_info.dwNumberOfProcessors;

			if(in_workers < 0)
				_worker_thread_count = cores() - 1;
			else _worker_thread_count = in_workers;

			//_functions = new TaskCallback[_thread_count];
			//_thread_data = new void*[_thread_count];
			_thread_masks = new LONGLONG[_worker_thread_count + 1];
			_thread_id = new int[_worker_thread_count + 1];
			_thread_id[0] = GetCurrentThreadId();
			_thread_states = 0;
				
			LONGLONG mask = 1;

			_task_queue = new TaskQueue();

			for(int k = 1; k <= _worker_thread_count; k++)
			{
				_thread_masks[k] = mask;
				mask = mask << 1i64;
				

				CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&Parallel::_run, (LPVOID)k, 0, NULL);
			}


		}

		void Parallel::finalize()
		{
			Parallel::join();

			_finalizing = true;

			delete _task_queue;

			

			delete[] _thread_masks;
			delete[] _thread_id;
		}

		int Parallel::threadID()
		{
			int win_thread_id = GetCurrentThreadId();
			
			for(int k = 0; k <= _worker_thread_count; k++)
				if(_thread_id[k] == win_thread_id)
					return k;

			return -1;
			
		}

		void Parallel::_run(int in_id)
		{
			// make things a litte clearer with references
			//TaskCallback& function = _functions[in_id];
			//void*& data = _thread_data[in_id];
			ULONGLONG mask = _thread_masks[in_id];
			ULONGLONG notmask = ~mask;
			_thread_id[in_id] = GetCurrentThreadId();
			Task* current_task = NULL;

			while(true)
			{
				int spins = 0;

				//while(function == NULL && _finalizing == false)
				while(_finalizing == false && (current_task = _task_queue->dequeue(mask)) == NULL)
				{
					if(spins++ < 10000) SwitchToThread();
					else Sleep(1);
				}
				
				// if we get here, the task_queue set the thread mask bit to 1

				// this will get set by finalize
				if(_finalizing) 	return;

				// call our function
				//(*function)(data);
				current_task->method(current_task->data);
				delete current_task;
				current_task = NULL;

				// set thread state to off
				InterlockedAnd64(&_thread_states, notmask);
			}
		}
	}
}